<template>
  <el-container style="width: 100%; height: 100%;">
    <el-main style="width: 70%; margin: 0 auto; padding-top: 20px;">
      <el-card shadow="hover" v-if="cartItems.length > 0">
        <h2 style="font-size: 24px; text-align: center; margin-bottom: 20px;">购物车</h2>

        <!-- Table for displaying cart items -->
        <el-table :data="cartItems" style="width: 100%;">
          <!-- Product Image -->
          <el-table-column label="图片" width="100">
            <template #default="scope">
              <el-image :src="scope.row.image || defaultImage" style="width: 80px; height: 80px;" />
            </template>
          </el-table-column>

          <!-- Product Name -->
          <el-table-column prop="name" label="商品名称" width="200">
          </el-table-column>
<!--          商品类型，1是环保产品，2是二手-->
          <el-table-column label="类型" width="100">
            <template #default="scope">
              {{ scope.row.type === 1 ? '环保产品' : '二手产品' }}
            </template>
          </el-table-column>


          <!-- Product Description -->
          <el-table-column prop="description" label="描述">
          </el-table-column>

          <!-- Price -->
          <el-table-column prop="price" label="价格" width="200">
            <template #default="scope">
              <span style="color: red;">￥{{ scope.row.price.toFixed(2) }}</span>
            </template>
          </el-table-column>

          <!-- Quantity -->
          <el-table-column label="数量" width="120">
            <template #default="scope">
              <el-input-number style="margin-left: -10%;width:100%" v-model="scope.row.nums" :min="1" @change="updateQuantity(scope.row)">
              </el-input-number>
            </template>
          </el-table-column>

          <!-- Total for each product -->
          <el-table-column label="小计" width="120">
            <template #default="scope">
              ￥{{ (scope.row.price * scope.row.nums).toFixed(2) }}
            </template>
          </el-table-column>

          <!-- Actions -->
          <el-table-column label="操作" width="200">
            <template #default="scope">
              <el-button type="danger" @click="removeFromCart(scope.row.id)">删除</el-button>
<!--              购买-->
              <el-button type="primary" @click="gotoBuy(scope.row.goodsId)">购买</el-button>

            </template>
          </el-table-column>
        </el-table>

        <!-- Total Price -->
        <div style="text-align: right; margin-top: 20px; font-size: 18px;">
          <strong>总计: </strong>
          <span style="color: red;">￥{{ totalAmount.toFixed(2) }}</span>
        </div>

        <!-- Buttons -->
        <div style="text-align: right; margin-top: 20px;">
          <el-button type="primary" @click="checkout">结算</el-button>
          <el-button @click="continueShopping">继续购物</el-button>
        </div>
      </el-card>

      <!-- Empty Cart Message -->
      <el-empty v-else description="购物车为空">
        <el-button type="primary" @click="continueShopping">去购物</el-button>
      </el-empty>
    </el-main>
  </el-container>
</template>

<script setup>
import { ref, computed } from 'vue';
import { getCartAPI, deleteCartAPI, updateCartAPI } from '@/api/Goods.js'; // 确保 updateCartAPI 方法正确导入
import { ElMessage, ElMessageBox } from 'element-plus';
import router from '@/router/index.js';
import { useUserStore } from "@/stores/user";

const userStore = useUserStore();
const cartItems = ref([]);
const defaultImage = 'https://via.placeholder.com/80'; // Placeholder image

// Fetch cart items
const fetchCartItems = async () => {
  console.log('Fetching cart items...');
  const response = await getCartAPI(userStore.UserId);
  if (response.data.code === 200) {
    cartItems.value = response.data.data;
  } else {
    ElMessage.error('获取购物车失败: ' + response.data.msg);
  }
};

// 删除购物车中的商品
const removeFromCart = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该商品吗？', '确认', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    });

    const response = await deleteCartAPI(id);
    if (response.data.code === 200) {
      ElMessage.success('已从购物车中删除商品');
      await fetchCartItems();
    } else {
      ElMessage.error('删除商品失败: ' + response.data.msg);
    }
  } catch (error) {
    if (error === 'cancel') {
      ElMessage.info('已取消删除');
    } else {
      ElMessage.error('删除商品失败: ' + error.message);
    }
  }
};

// 更新购物车商品数量
const updateQuantity = async (item) => {
  try {
    const response = await updateCartAPI(item.id, item.nums); // 调用后端接口更新购物车数量
    if (response.data.code === 200) {
      ElMessage.success(`已更新 ${item.name} 的数量`);
    } else {
      ElMessage.error('更新商品数量失败: ' + response.data.msg);
    }
  } catch (error) {
    ElMessage.error('更新商品数量失败: ' + error.message);
  }
};

// Compute the total amount
const totalAmount = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.nums, 0);
});
//跳转到购买页面
const gotoBuy = (goodsId) => {

  router.push({
    path: '/buy',
    query: {
      productId: goodsId // Product ID
    }
  });
};
// Checkout
const checkout = () => {
  ElMessage('结算功能待开发...');
};

// Continue shopping
const continueShopping = () => {
  router.push('/layout/second'); // Assuming there's a route for the shop page
};

// Fetch cart items on component mount
fetchCartItems();
</script>

<style scoped>
.el-card {
  padding: 20px;
  border-radius: 10px;
}

h2 {
  color: #333;
}
</style>
